
/**
 * Created by wangjiakun on 2018/6/14 0014.
 */
import React from 'react';

import { messages, getApprovelHistory, queryCurrencyPrecision, currencyPrecisionCal } from 'share/common';
import { connect } from 'react-redux';
import {Form, Row, Col, Select, InputNumber } from 'antd'
const FormItem = Form.Item;
const Option = Select.Option;
import 'styles/expense-reimbursement-control/expense-standard/subsidy-rule/subsidy-rule.scss';
import 'styles/request/travel-request/travel-type.scss';
import 'styles/custom-fields.scss'
import ruleUtil from 'containers/expense-reimbursement-control/expense-standard/subsidy-rule/subsidy-rule-util';

class CalculateForm extends React.Component{
  returnValue = {
    isUseStandard:true,//是否引用不标准
    restriction:1001,//操作符
    divisor:1,//因数
    amount:0,//金额最终值
  }
  isUpdate = false;
  constructor(props){
    super(props);
    this.state = {
      isUseStandard:true,//是否引用不标准
      restriction:1001,//操作符
      divisor:1,//因数
      amount:0,//金额最终值
      baseAmount:0,
    }
  }

  componentDidMount(){
    const { value, standardAmount } = this.props;
    if(value && value.needUpdate){//编辑
      this.returnValue = JSON.parse(JSON.stringify(value));
      this.setState({
        isUseStandard: value.isUseStandard === null ? false : value.isUseStandard,//是否引用不标准
        restriction: value.restriction === null ? 1001 : value.restriction,//操作符
        divisor: value.divisor === null ? 1 : value.divisor,//因数
        amount: value.amount === null ? standardAmount : value.amount,//金额最终值
        baseAmount: value.isUseStandard ? 0 : value.amount === null ? 0 : parseFloat(currencyPrecisionCal(this.props.currentCode, value.amount)),
      },()=>{
        this.props.form.resetFields();
      })
    }else {//新建
      this.setState({amount:ruleUtil.calculateWeek('*',this.props.standardAmount,1)},()=>{
        this.props.form.resetFields();
        this.returnValue.amount = this.state.amount;
        this.onChange();
      });
    }
    this.onChange();
  }

  componentWillReceiveProps(nextProps){
    if(this.props.standardAmount !== nextProps.standardAmount){
        this.updateWeekAmount();
    }
    if (this.props.currentCode !== nextProps.currentCode && this.props.form.getFieldValue('baseAmount')) {
      this.props.form.setFieldsValue({'baseAmount': parseFloat(currencyPrecisionCal(nextProps.currentCode, this.props.form.getFieldValue('baseAmount')))});
    }
  }

  updateWeekAmount = (isSet) =>{
    setTimeout(()=>{
      let value = this.props.form.getFieldValue('restriction');
      let baseNum = this.props.form.getFieldValue('divisor');
      let standard = this.props.standardAmount;
      let amount = ruleUtil.calculateWeek(value,standard,baseNum);
      this.returnValue.isUseStandard = this.props.form.getFieldValue('isUseStandard') === 'true' ? true : false;
      this.returnValue.amount = this.returnValue.isUseStandard ? amount : this.props.form.getFieldValue('baseAmount');
      this.returnValue.divisor = baseNum;
      this.returnValue.restriction = ruleUtil.restrictionChange(value);
      this.onChange();
      this.setState({amount:amount});
    },150)
  }

  onChange = () =>{
    const onChange = this.props.onChange;
    delete this.returnValue.reset;
    if (onChange) {
      onChange(this.returnValue);
    }
  };

  render(){
    const { amount,isUseStandard, restriction, divisor, baseAmount} = this.state;
    const { getFieldDecorator } = this.props.form;
    const { currentCode,labelName, standardAmount,disabled } = this.props;
    return(
      <div className="subsidy-rules">
        <Row className="new-subsidy-rule">
          <Col span={6} className="form-label" style={{paddingTop:1}}>{labelName}:</Col>
          <Col span={18} style={{display:'flex'}}>
            <FormItem>
              {getFieldDecorator('isUseStandard',{
                initialValue:JSON.stringify(isUseStandard)
              })(
                <Select
                  disabled={disabled}
                  onSelect={this.updateWeekAmount}
                  getPopupContainer={triggerNode => triggerNode.parentNode}
                  style={{width:180}}>
                  <Option value={'true'}>{messages('setting.key1088'/*引用标准差补*/)}</Option>
                  <Option value={'false'}>{messages('setting.key1089'/*固定值*/)}</Option>
                </Select>
              )}
            </FormItem>
            {
              this.props.form.getFieldValue('isUseStandard') === 'true' ? <div style={{display:'flex'}}>
                <FormItem className="form-item-content">
                  {getFieldDecorator('restriction',{
                    initialValue: ruleUtil.restrictionChange(restriction)
                  })(
                    <Select onSelect={this.updateWeekAmount}
                            disabled={disabled}
                            getPopupContainer={triggerNode => triggerNode.parentNode}>
                      <Option value="+">+</Option>
                      <Option value="-">-</Option>
                      <Option value="*">*</Option>
                      <Option value="/">/</Option>
                    </Select>
                  )}
                </FormItem>
                <FormItem className="form-item-content">
                  {getFieldDecorator('divisor',{
                    initialValue:divisor
                  })(<InputNumber disabled={disabled} onChange={this.updateWeekAmount} step={1} precision={3} min={0}/>)}
                </FormItem>
                <span style={{marginLeft:'42px',color:(amount < 0 || amount === undefined) ? 'red':'#404040'}}>
                  {` = ${currentCode} ${amount === null ? currencyPrecisionCal(currentCode, standardAmount) : (amount === undefined ? '': currencyPrecisionCal(currentCode, amount))}`}
                </span>
              </div>:<FormItem className="form-item-content">
                {getFieldDecorator('baseAmount',{
                  initialValue: baseAmount
                })(<InputNumber disabled={disabled} onChange={this.updateWeekAmount} step={1} precision={queryCurrencyPrecision(currentCode)} min={0}/>)}
              </FormItem>
            }
          </Col>
        </Row>
      </div>
    )
  }

}

CalculateForm.propTypes = {
  currentCode:React.PropTypes.string,
  labelName:React.PropTypes.string,
  value:React.PropTypes.object,
  onChange:React.PropTypes.func,
  standardAmount:React.PropTypes.number,
  disabled:React.PropTypes.bool,
}

CalculateForm.defaultProps = {
  value:{
    isUseStandard:true,//是否引用不标准
    restriction:1001,//操作符
    divisor:1,//因数
    amount:0,//金额最终值
    disabled:false,
  },
}

function mapStateToProps(state) {
  return {}
}

const wrappedCalculateForm = Form.create()(CalculateForm);

export default connect(mapStateToProps)(wrappedCalculateForm);
